<?php
class RepostsController extends AppController {

	var $name = 'Reposts';
	var $helpers = array('Html', 'Form');
	
	function beforeFilter(){
		parent::beforeFilter();
		$this->Auth->allow('');
	}
	
	function isOwner( $repost_id=NULL ){
		if($this->Auth->user('group_id')==1){
			return true;
		}
		
		if($this->Repost->hasAny(
			array(
				'Repost.id'=>$repost_id, 
				'Repost.user_id'=>$this->Auth->user('id')
			)
		)){
			return true;
		} else {
			return false;	
		}
	}
	
	function add() {
		if (!empty($this->data)) {
			$this->data['Repost']['ptime']=strtotime(date('Y-m-d H:i:s'));
			
			$this->Repost->create();
			if ($this->Repost->save($this->data)) {
				$this->Session->setFlash(__('The Repost has been saved', true));
				$this->redirect($this->Session->read('History.Pre'));
			} else {
				$this->Session->setFlash(__('The Repost could not be saved. Please, try again.', true));
				$this->redirect($this->Session->read('History.Pre'));
			}
		}
		$users = $this->Repost->User->find('list');
		$posts = $this->Repost->Post->find('list');
		$this->set(compact('users', 'posts'));
	}

	function edit($id = null) {
		if(!$this->isOwner($id)){
			$this->Session->setFlash(__('沒有進行此動作的權限', true));
			$this->redirect(array('controller'=>'bulletins', 'action'=>'index'));
		}
		
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid Repost', true));
			$this->redirect($this->Session->read('History.Pre'));
		}
		if (!empty($this->data)) {
			if ($this->Repost->save($this->data)) {
				$this->Session->setFlash(__('The Repost has been saved', true));
				$this->redirect($this->Session->read('History.Pre'));
			} else {
				$this->Session->setFlash(__('The Repost could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Repost->read(null, $id);
			$this->set('data', $this->data);
		}
		$users = $this->Repost->User->find('list');
		$posts = $this->Repost->Post->find('list');
		$this->set(compact('users','posts'));
	}

	function delete($id = null) {
		if(!$this->isOwner($id)){
			$this->Session->setFlash(__('沒有進行此動作的權限', true));
			$this->redirect(array('controller'=>'bulletins', 'action'=>'index'));
		}
		
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for Repost', true));
			$this->redirect($this->Session->read('History.Pre'));
		}
		if ($this->Repost->del($id)) {
			$this->Session->setFlash(__('Repost deleted', true));
			$this->redirect($this->Session->read('History.Pre'));
		}
	}

}
?>